package com.zn.controller;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @Description
 * @Author zhaoning
 * @Date 2024/7/21
 */
public class PostMessageController {
    public static final String API_KEY = "AJ085KPVqyTOPiwayT4huZ8h";
    public static final String SECRET_KEY = "nCppmGzzDKvC9FlaOu54TFVf5FttIzv2";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getAnswerBaidu(Integer id, String content, String text) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        // "{\"user_id\":\"1001\",
        // \"messages\":
        // [{\"role\":\"user\",\"content\":\"您好\"},
        // {\"role\":\"assistant\",\"content\":\"您好！有什么我可以帮助您的吗？请随时告诉我。\"},
        // {\"role\":\"user\",\"content\":\"帮我查查今年有多少天\"},
        // {\"role\":\"assistant\",\"content\":\"您好！根据常规的公历制度，今年的天数即2023年有365天。 希望以上信息对您有所帮助！\"}],
        RequestBody body = RequestBody.create(mediaType, "{\"user_id\":\"" + id + "\","
                + "\"messages\":["+ getIgnoreEnter(content) + "],"
                + "\"penalty_score\":1," +
                "\"enable_system_memory\":false," +
                "\"disable_search\":false," +
                "\"enable_citation\":false," +
                "\"enable_trace\":false}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-lite-8k?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        String str = HTTP_CLIENT.newCall(request).execute().body().string();
        System.out.println(str);
        return str;
    }

    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        assert response.body() != null;
        return new JSONObject(response.body().string()).getString("access_token");
    }

    static String getIgnoreEnter(String string) throws IOException {
        string = string.replace('\n', ',');

        return string;
    }
}
